<?php

namespace app\api\controller;

use app\common\controller\Api;
use  app\admin\model\Users as userss;
use  think\Db;
use think\Env;
use fast\Random;
use think\Log;

/**
 * 支付相关接口
 */
class Pay extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $redis;
    private $appid;
    private $secret;
    private $merchantId;
    private $openid;
    private $merchantSerialNumber;

    public function _initialize()
    {
        parent::_initialize();

        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
        $this->appid = Env::get('wechat.appid');
        $this->secret = Env::get('wechat.secret');
        // 商户相关配置，
        //$this->merchantId = '1607664177'; // 商户号
        //$this->merchantSerialNumber = '30F527B52B72556E46DCFD5FC367EA2333264F08'; // 商户API证书序列号

        // 商户相关配置路得，
        $this->merchantId = '1612124491'; // 商户号
        $this->merchantSerialNumber = '7B1DE72A98B844B1E6FB31F7907B0318A075EC77'; // 商户API证书序列号

        $this->openid = empty($_SERVER['HTTP_OPENID']) ? $this->error('openid不能为空',[],'401'):$_SERVER['HTTP_OPENID'];//获取openid

        $this->user_arr = Db::table('fa_users')
            ->where('openid',$this->openid)
            ->find();

        if (empty($this->user_arr)){
            $this->error('用户信息为空',[],'401');
        }

    }

    /**
     *
     * 统一下单接口
     */
    public function wechartAddOrder(){
        $money = empty(request()->post('money')) ? $this->error('money不能为空'):request()->post('money');
        $info_id = empty(request()->post('info_id')) ? $this->error('info_id不能为空'):request()->post('info_id');
        $medic_id = empty(request()->post('medic_id')) ? $this->error('medic_id不能为空'):request()->post('medic_id');
        $project = empty(request()->post('project')) ? $this->error('project不能为空'):request()->post('project');
        $project_ids = empty(request()->post('project_ids')) ? $this->error('project_ids不能为空'):request()->post('project_ids');
        //$working_id = empty(request()->post('working_id')) ? $this->error('working_id不能为空'):request()->post('working_id');
        $date_time = empty(request()->post('date')) ? $this->error('date不能为空'):request()->post('date');

        //$money = 1;

        $info_arr = Db::table('fa_info')
            ->where('id',$info_id)
            ->find();

        if ($info_arr['binding'] != 0){
            $users_id = $info_arr['binding'];
        }else{
            $users_id =  $this->user_arr['id'];
        }


        $ordernumber = get_strings(16,2);

        $insert = Db::table('fa_registration')
            ->insertGetId([
                'user_id' => $users_id,
                'info_id' => $info_id,
                'medic_id' => $medic_id,
                'project' => $project,
                'visiting_time' => $date_time,
                'begin_time' => strtotime($date_time.' 00:00:00'),
                'end_time' => strtotime($date_time.' 23:59:59'),
                //'status' => '待支付',
                'status' => '待确认',
                'price' => $money,
                'create_time' =>time(),
                //'working_id' =>$working_id,
                'code' =>$ordernumber,
                'date' =>$date_time,
                'project_ids' =>$project_ids,
            ]);
        //$insert = 1;

        if($insert > 0){
            //$this->success('成功',[]);
            //组装需要的数据
            $arr = [
                'info_id' => $info_id,
                'user_id' => $users_id,
                'order_id' => $insert,
                //'project' => $project,
                //'working_id' => $working_id,
                //'date' => $date_time,
                //'project_ids' => $project_ids,
            ];
            $arr_str = json_encode($arr);

            $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
            $urlarr = parse_url($url);
            $appid = $this->appid;//appID
            $mchid = $this->merchantId;//商户ID
            $xlid = $this->merchantSerialNumber;//API序列号
            $data = array();
            $randstr = get_strings(16,2);//随机字符串长度不超过32
            $time = time();
            $data['appid'] = $appid;
            $data['mchid'] = $mchid;
            $data['description'] = '预约挂诊费';//商品描述
            $data['out_trade_no'] = $ordernumber;//订单编号
            $data['attach'] = $arr_str;//自定义参数说明
            //$data['notify_url'] = "https://www.weixin.qq.com/wxpay/pay.php";//回调接口
            $data['notify_url'] = "https://www.looin.cn/api/users/callbacks";//回调接口
            $data['amount']['total'] = intval($money);//金额
            $data['payer']['openid'] = $this->openid;//用户openID
            $data = json_encode($data);
            $key = $this->getSign($data,$urlarr['path'],$randstr,$time);//签名
            $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$randstr,$time,$key);//头部信息
            $header  = array(
                'Content-Type:'.'application/json; charset=UTF-8',
                'Accept:application/json',
                'User-Agent:*/*',
                'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
            );
            $ret = curl_post_https($url,$data,$header);
            $ret = json_decode($ret,true);

            if (isset($ret['code'])){
                write_log($ret);
                $this->success('失败',$ret);
            }

            $ret['code'] = $ordernumber;
            $ret['time'] = date('Y-m-d H:i:s');
            write_log($ret);
            $this->success('成功',$ret);




        }else{
            $this->error('订单生成失败',$insert);
        }

    }


    /**
     * 下单接口
     *
     */
    public function wechartAddOrders(){
//        try{
            $order_id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

            $order_data = Db::table('fa_registration')
                ->where('id',$order_id)
                ->find();

            if (empty($order_data)){
                $this->success('订单错误',[]);
            }

//            if ($order_data['user_id'] != $this->user_arr['id']){
//                $this->success('用户信息错误',[]);
//            }
            $info_id = $order_data['info_id'];
            //$ordernumber = $order_data['code'];
            $ordernumber = get_strings(16,2);
            $money = $order_data['price'];


            //组装需要的数据
            $arr = [
                'info_id' => $info_id,
                'user_id' => $this->user_arr['id'],
                'order_id' => $order_data['id'],
                //'project' => $project,
                //'working_id' => $working_id,
                //'date' => $date_time,
                //'project_ids' => $project_ids,
            ];
            $arr_str = json_encode($arr);

            $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
            $urlarr = parse_url($url);
            $appid = $this->appid;//appID
            $mchid = $this->merchantId;//商户ID
            $xlid = $this->merchantSerialNumber;//API序列号
            $data = array();
            $randstr = get_strings(16,2);//随机字符串长度不超过32
            $time = time();
            $data['appid'] = $appid;
            $data['mchid'] = $mchid;
            $data['description'] = '预约挂诊费';//商品描述
            $data['out_trade_no'] = $ordernumber;//订单编号
            $data['attach'] = $arr_str;//自定义参数说明
            //$data['notify_url'] = "https://www.weixin.qq.com/wxpay/pay.php";//回调接口
            $data['notify_url'] = "https://www.looin.cn/api/users/callbacks";//回调接口
            $data['amount']['total'] = intval($money);//金额
            $data['payer']['openid'] = $this->openid;//用户openID
            $data = json_encode($data);
            $key = $this->getSign($data,$urlarr['path'],$randstr,$time);//签名
            $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$randstr,$time,$key);//头部信息
            $header  = array(
                'Content-Type:'.'application/json; charset=UTF-8',
                'Accept:application/json',
                'User-Agent:*/*',
                'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
            );
            $ret = curl_post_https($url,$data,$header);
            $ret = json_decode($ret,true);

            if (isset($ret['code'])){
                write_log($ret);
                $this->success('失败',$ret);
            }


            $ret['port'] = 'wechartAddOrders';
            $ret['code'] = $ordernumber;
            $ret['time'] = date('Y-m-d H:i:s');
            write_log($ret);
            $this->success('成功',$ret);
//        }catch(\Exception $e){
//            write_log($e->getMessage());
//            $this->error($e->getMessage());
//        }

    }


    /**
     * 周边产品下单接口
     *
     */
    public function add_orders(){
        $type = empty(request()->post('type')) ? $this->error('type不能为空'):request()->post('type');
        $products_id = empty(request()->post('products_id')) ? $this->error('products_id不能为空'):request()->post('products_id');
        //$money = empty(request()->post('money')) ? $this->error('money不能为空'):request()->post('money');
        $contacts = empty(request()->post('contacts')) ? $this->error('contacts不能为空'):request()->post('contacts');
        $phone = empty(request()->post('phone')) ? $this->error('phone不能为空'):request()->post('phone');
        $phone = is_phone($phone);

        if ($phone === false){
            $this->error('手机号格式错误',[]);
        }

        $product_arr = Db::table('fa_products')
            ->where('id',$products_id)
            ->find();

        if (empty($product_arr)){
            $this->error('产品数据为空',[]);
        }

        $money = $product_arr['price']*100;
        $ordernumber = get_strings(16,2);

        //1代表商品，2代表场所
        if ($type == 1){
            $is_send = empty(request()->post('is_send')) ? $this->error('is_send不能为空'):request()->post('is_send');
            $site = empty(request()->post('site')) ? '':request()->post('site');

            if ($product_arr['type'] != '商品'){
                $this->error('该产品不是商品',[]);
            }

            $insert = Db::table('fa_orders')
                ->insertGetId([
                    'user_id' => $this->user_arr['id'],
                    'code' => $ordernumber,
                    'products_id' => $products_id,
                    //'status' => 0,
                    'status' => 1,
                    'contacts' => $contacts,
                    'phone' => $phone,
                    'money' => $money,
                    'is_send' => $is_send,
                    'site' => $site,
                    'create_time' => time(),
                    'type' => 1,
                ]);

        }elseif ($type == 2){
            $date = empty(request()->post('date')) ? $this->error('date不能为空'):request()->post('date');
            $pan = date('w',strtotime($date));

            if ($product_arr['type'] != '场所'){
                $this->error('该产品不是场所',[]);
            }

            if ($date < date('Y-m-d')){
                $this->error('预约日期不能小于今天',[]);
            }

            //判断预约日期是否营业
            if ($product_arr['opening_hours'] != 8){
                if ($product_arr['opening_hours'] != $pan){
                    $this->error('预约日期不开放',[]);
                }
            }

            $pan_arr = Db::table('fa_orders')
                ->where(['date'=>$date,'status'=>1])
                ->find();

            if (!empty($pan_arr)){
                $this->error('该日期已被预约',[]);
            }

            $insert = Db::table('fa_orders')
                ->insertGetId([
                    'user_id' => $this->user_arr['id'],
                    'code' => $ordernumber,
                    'products_id' => $products_id,
                    //'status' => 0,
                    'status' => 1,
                    'contacts' => $contacts,
                    'phone' => $phone,
                    'money' => $money,
                    'date' => $date,
                    'create_time' => time(),
                    'type' => 2,
                ]);


        }else{
            $this->error('type参数错误',[]);
        }

        if($insert > 0){
            //组装需要的数据
            $arr = [
                'order_id' => $insert,
            ];
            $arr_str = json_encode($arr);

            $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
            $urlarr = parse_url($url);
            $appid = $this->appid;//appID
            $mchid = $this->merchantId;//商户ID
            $xlid = $this->merchantSerialNumber;//API序列号
            $data = array();
            $randstr = get_strings(16,2);//随机字符串长度不超过32
            $time = time();
            $data['appid'] = $appid;
            $data['mchid'] = $mchid;
            $data['description'] = '商品价格';//商品描述
            $data['out_trade_no'] = $ordernumber;//订单编号
            $data['attach'] = $arr_str;//自定义参数说明
            //$data['notify_url'] = "https://www.weixin.qq.com/wxpay/pay.php";//回调接口
            $data['notify_url'] = "https://www.looin.cn/api/users/callbackss";//回调接口
            $data['amount']['total'] = intval($money);//金额
            $data['payer']['openid'] = $this->openid;//用户openID
            $data = json_encode($data);
            $key = $this->getSign($data,$urlarr['path'],$randstr,$time);//签名
            $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$randstr,$time,$key);//头部信息
            $header  = array(
                'Content-Type:'.'application/json; charset=UTF-8',
                'Accept:application/json',
                'User-Agent:*/*',
                'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
            );
            $ret = curl_post_https($url,$data,$header);
            $ret = json_decode($ret,true);

            if (isset($ret['code'])){
                write_log($ret);
                $this->success('失败',$ret);
            }


            $ret['code'] = $ordernumber;
            $ret['time'] = date('Y-m-d H:i:s');
            write_log($ret);
            $this->success('成功',$ret);


        }else{
            $this->error('订单生成失败',$insert);
        }


    }


    /**
     * 周边产品再次下单接口
     *
     */
    public function add_orderss(){
        $order_id = empty(request()->post('id')) ? $this->error('id不能为空'):request()->post('id');

        $order_data = Db::table('fa_orders')
            ->where('id',$order_id)
            ->find();

        if (empty($order_data)){
            $this->success('订单错误',[]);
        }

        if ($order_data['user_id'] != $this->user_arr['id']){
            $this->success('用户信息错误',[]);
        }

        $ordernumber = get_strings(16,2);
        $money = $order_data['money'];

        //组装需要的数据
        $arr = [
            'order_id' => $order_data['id'],
        ];
        $arr_str = json_encode($arr);

        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        $urlarr = parse_url($url);
        $appid = $this->appid;//appID
        $mchid = $this->merchantId;//商户ID
        $xlid = $this->merchantSerialNumber;//API序列号
        $data = array();
        $randstr = get_strings(16,2);//随机字符串长度不超过32
        $time = time();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['description'] = '商品价格';//商品描述
        $data['out_trade_no'] = $ordernumber;//订单编号
        $data['attach'] = $arr_str;//自定义参数说明
        //$data['notify_url'] = "https://www.weixin.qq.com/wxpay/pay.php";//回调接口
        $data['notify_url'] = "https://www.looin.cn/api/users/callbackss";//回调接口
        $data['amount']['total'] = intval($money);//金额
        $data['payer']['openid'] = $this->openid;//用户openID
        $data = json_encode($data);
        $key = $this->getSign($data,$urlarr['path'],$randstr,$time);//签名
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$randstr,$time,$key);//头部信息
        $header  = array(
            'Content-Type:'.'application/json; charset=UTF-8',
            'Accept:application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
        );
        $ret = curl_post_https($url,$data,$header);
        $ret = json_decode($ret,true);

        if (isset($ret['code'])){
            write_log($ret);
            $this->success('失败',$ret);
        }


        $ret['port'] = 'add_orderss';
        $ret['code'] = $ordernumber;
        $ret['time'] = date('Y-m-d H:i:s');
        write_log($ret);
        $this->success('成功',$ret);

    }


    /**
     * 调起支付的签名
     * @param $post
     * @return string
     *
     */
    public function getWechartSign(){
        $package = empty(request()->post('prepay_id')) ? $this->error('prepay_id不能为空'):request()->post('prepay_id');

        $data = array();
        $data['timeStamp'] = time();
        $data['nonceStr'] = get_strings(32);
        $data['package'] = 'prepay_id='.$package;
        $str = $this->appid."\n".$data['timeStamp']."\n".$data['nonceStr']."\n".$data['package']."\n";
        $key = file_get_contents('../key.pem');
        $str = getSha256WithRSA($str,$key);

        $arr = [
            'timeStamp' => (string)$data['timeStamp'],
            'nonceStr' => $data['nonceStr'],
            'package' => $data['package'],
            'paySign' => $str,
        ];

        $this->success('成功',$arr);
    }


    //微信支付签名
    public function getSign($data=array(),$url,$randstr,$time){
        $str = "POST"."\n".$url."\n".$time."\n".$randstr."\n".$data."\n";
        $key = file_get_contents('../key.pem');//在商户平台下载的秘钥
        $str = getSha256WithRSA($str,$key);
        return $str;
    }


    //微信回调写入日志文件并返回
    public function writeWechartLog(){
        //https://www.jianshu.com/p/c88c72d0121b
        $strs = 'BqpuRjJvyghmkcsFv07ChBgLelWBhcvCtcaOr9J8BD2UOLdf+pRTpbU+R+PBN1GG71j2JcS8tPGCH5o49o/GYR9fMOdZM953vuI1A/ajiQmNFRfQxBfb09vAhdgzshvnqOOJfLYlVYyxjbjlSkX2yDLg/YQ310xqqMlnfcUqdNmtoCY3uWWvLO4N97zzeZ8hlpWnUQu3D/k+bBr3VqBhzoK1YsqtsSp3jExIWw13PD4O1YUEATESeRnwoRAHi2zWh7Po2x097WkBcF0J7TlEKU6CrCP0jLvZy4as5tluYLa8mvxswbnJGvY4OhToAfPP6Ephtm+uscA7EbgENYbghoGvROxTG4qL0s0dbCgF0AOjPoNKd3MK3f51NMqBgCNkSyF5PR9Zx/NWXghp1jd33Z2CDuX+WPe/gjAyLVcfa1O3r2BxR8UilFD7OKkGCCkL7YCtEhn8F+c5Ktmt05EOqeJPA23EjwM0mVeeaC2q+3g6l5sPzlhAv4ZjvQpcijUdWsnMkpdIizt3QSMyAKjDju812tN58DuaD8tRGdqPAat7yrMBnB5JIV/s0fjS9Vi//rizR6hMko84qS9ZW+x2HlB7Bg/FKJlVlRDt9RvIt1gvvrgh2WuunFb7Nk6yWZFFdpBoVQY8ayptFyGjrwyyxz3C+cZ5OGYJ99hgHUaNJQNUeZsviraj7iNW62yvPkZcmuu4MkNWZRxR3Fk/3jNgk/sp/TlZYKlFdNvf3qzxcg==';
        $post = input('');
        $key = '';//商户平台设置的api v3 密码
        //$text = base64_decode($post['resource']['ciphertext']);
        $text = base64_decode($strs);
        $str = sodium_crypto_aead_aes256gcm_decrypt($text,'transaction','yq8j3MFHSc4d',$key);
        $res = json_decode($str, true);

        var_dump($res);die();

        if($res['trade_state'] == 'SUCCESS'){
            //成功操作
        }

        var_dump($post);die();
    }
}
